

#import "ALAssetsPickerController.h"
#import "ALCameraCell.h"
#import "ALGroupPickerView.h"
#import "ALCameraViewController.h"

@interface ALAssetsPickerController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (strong, nonatomic)  UIButton *btnClose;
@property (strong, nonatomic)  UIButton *btnTitle;
@property (strong, nonatomic)  UIView *navigationTop;

@property (nonatomic, strong) UIView *noAssetView;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIImagePickerController *picker;
@property (nonatomic, strong) ALGroupPickerView *groupPicker;

@property (nonatomic, strong) ALAssetsGroup *assetsGroup;
@property (nonatomic, strong) NSMutableArray *groups;
@property (nonatomic, strong) ALAssetsLibrary *assetsLibrary;
@property (nonatomic, strong) NSMutableArray *assets;
@end

@implementation ALAssetsPickerController
#pragma mark - ALAssetsLibrary
+ (ALAssetsLibrary *)defaultAssetsLibrary
{
    static dispatch_once_t pred = 0;
    static ALAssetsLibrary *library = nil;
    dispatch_once(&pred,^
                  {
                      library = [[ALAssetsLibrary alloc] init];
                  });
    return library;
}
- (void)dealloc
{
    self.assetsLibrary = nil;
    self.assetsGroup = nil;
    self.assets = nil;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    self.navigationTop=[[UIView alloc]
                        initWithFrame:CGRectMake(0, 0, 750/2, 64)];
	[self.navigationTop setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:self.navigationTop];
    
    self.btnClose=[UIButton buttonWithType:UIButtonTypeCustom];
	[self.btnClose setFrame:CGRectMake(40/2-10,
									   (self.navigationTop.frame.size.height-26/2)/2+20/2-10,
									   26/2+20,
									   26/2+20)];
    [self.btnClose addTarget:self
					  action:@selector(btnAction:)
			forControlEvents:UIControlEventTouchUpInside];
    [self.btnClose setTag:kTagButtonClose];
    [self.btnClose setImage:[UIImage imageNamed:@"CameraPicker.bundle/Camera_Close"] forState:UIControlStateNormal];
	[self.btnClose setImageEdgeInsets:UIEdgeInsetsMake(10, 10, 10, 10)];
    [self.navigationTop addSubview:self.btnClose];
	
    self.btnTitle=[UIButton buttonWithType:UIButtonTypeCustom];
	[self.btnTitle setBackgroundColor:[UIColor clearColor]];
    [self.btnTitle setFrame:CGRectMake((750/2-220/2)/2, 10, 220/2, 40)];
	[self.btnTitle setCenter:CGPointMake(self.btnTitle.center.x, self.btnClose.center.y)];
    [self.btnTitle addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
	[self.btnTitle setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.btnTitle setTag:kTagButtonGroupPicker];
    [self.navigationTop addSubview:self.btnTitle];
	
    [self initVariable];
    [self initImagePicker];
    [self setupOneMediaTypeSelection];
    
    __weak typeof(self) weakSelf = self;
    [self setupGroup:^{
        [weakSelf.groupPicker.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
    } withSetupAsset:YES];
    [self setupCollectionView];
    [self setupGroupPickerview];
    [self initNoAssetView];
}
- (void)initVariable
{
    self.assetsFilter = [ALAssetsFilter allPhotos];
    self.view.clipsToBounds = YES;
}
- (void)initImagePicker
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = NO;
    picker.videoQuality = UIImagePickerControllerQualityTypeHigh;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.mediaTypes =
        [UIImagePickerController availableMediaTypesForSourceType:
         UIImagePickerControllerSourceTypeCamera];
    }
    self.picker = picker;
}
- (void)initNoAssetView
{
    UIView *noAssetsView    = [[UIView alloc] initWithFrame:self.collectionView.bounds];
    
    CGRect rect             = CGRectInset(self.collectionView.bounds, 10, 10);
    UILabel *title          = [[UILabel alloc] initWithFrame:rect];
    UILabel *message        = [[UILabel alloc] initWithFrame:rect];
    
    title.text              = NSLocalizedString(@"No Photos or Videos", nil);
    title.font              = [UIFont systemFontOfSize:19.0];
    title.textColor         = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1];
    title.textAlignment     = NSTextAlignmentCenter;
    title.numberOfLines     = 5;
    title.tag               = kTagNoAssetViewTitleLabel;
    
    message.text            = NSLocalizedStringFromTable(@"You can sync photos and videos onto your iPhone using iTunes.", @"ALAssetsPickerController",nil);
    message.font            = [UIFont systemFontOfSize:15.0];
    message.textColor       = [UIColor colorWithRed:153.0/255.0 green:153.0/255.0 blue:153.0/255.0 alpha:1];
    message.textAlignment   = NSTextAlignmentCenter;
    message.numberOfLines   = 5;
    message.tag             = kTagNoAssetViewMsgLabel;
    
    UIImageView *titleImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CameraPicker.bundle/Camera_ico_no_image"]];
    titleImage.contentMode = UIViewContentModeCenter;
    titleImage.tag = kTagNoAssetViewImageView;
    
    [title sizeToFit];
    [message sizeToFit];
    
    title.center            = CGPointMake(noAssetsView.center.x, noAssetsView.center.y - 10 - title.frame.size.height / 2 + 40);
    message.center          = CGPointMake(noAssetsView.center.x, noAssetsView.center.y + 10 + message.frame.size.height / 2 + 20);
    titleImage.center       = CGPointMake(noAssetsView.center.x, noAssetsView.center.y - 10 - titleImage.frame.size.height /2);
    [noAssetsView addSubview:title];
    [noAssetsView addSubview:message];
    [noAssetsView addSubview:titleImage];
    
    [self.collectionView addSubview:noAssetsView];
    self.noAssetView = noAssetsView;
    self.noAssetView.hidden = YES;
}
- (void)setupGroupPickerview
{
    __weak typeof(self) weakSelf = self;
    self.groupPicker = [[ALGroupPickerView alloc] initWithGroups:self.groups];
    self.groupPicker.blockTouchCell = ^(NSInteger row){
        [weakSelf changeGroup:row filter:weakSelf.assetsFilter];
    };
	
	[self.view addSubview:self.groupPicker];
    [self.view bringSubviewToFront:self.navigationTop];
    [self menuArrowRotate];
}
- (void)setupOneMediaTypeSelection
{
    self.assetsFilter = [ALAssetsFilter allPhotos];
}
- (void)setupCollectionView
{
    UICollectionViewFlowLayout *layout  = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize                     = kThumbnailSize;
    layout.sectionInset                 = UIEdgeInsetsMake(1.0, 0, 0, 0);
    layout.minimumInteritemSpacing      = .5;
    layout.minimumLineSpacing           = .5;
    
    self.collectionView = [[UICollectionView alloc]
						   initWithFrame:CGRectMake(0, 64,750/2 ,
													self.view.bounds.size.height - 64)
						   collectionViewLayout:layout];
    self.collectionView.allowsMultipleSelection = YES;
    [self.collectionView registerClass:[ALCameraCell class]
			forCellWithReuseIdentifier:kAssetsViewCellIdentifier];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.bounces = YES;
    self.collectionView.alwaysBounceVertical = YES;
    
    [self.view insertSubview:self.collectionView atIndex:0];
}

- (void)changeGroup:(NSInteger)item filter:(ALAssetsFilter *)filter
{
    self.assetsFilter = filter;
    self.assetsGroup = self.groups[item];
    [self setupAssets:nil];
    [self.groupPicker.tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:item inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
    [self.groupPicker dismiss:YES];
    [self menuArrowRotate];
}
- (void)changeAssetType:(BOOL)isPhoto endBlock:(voidBlock)endBlock
{
    if(isPhoto)
    {
        self.assetsFilter = [ALAssetsFilter allPhotos];
        [self setupAssets:endBlock];
    }
    
}
- (void)setupGroup:(voidBlock)endblock withSetupAsset:(BOOL)doSetupAsset
{
    if (!self.assetsLibrary)
    {
        self.assetsLibrary = [self.class defaultAssetsLibrary];
    }
    if (!self.groups)
        self.groups = [[NSMutableArray alloc] init];
    else
        [self.groups removeAllObjects];
	__weak typeof(self) weakSelf = self;
    ALAssetsFilter *assetsFilter = [ALAssetsFilter allAssets];
    ALAssetsLibraryGroupsEnumerationResultsBlock resultsBlock = ^(ALAssetsGroup *group, BOOL *stop) {
        if (group)
        {
            [group setAssetsFilter:assetsFilter];
            NSInteger groupType = [[group valueForProperty:ALAssetsGroupPropertyType] integerValue];
            if(groupType == ALAssetsGroupSavedPhotos)
            {
                [weakSelf.groups insertObject:group atIndex:0];
                if(doSetupAsset)
                {
                    weakSelf.assetsGroup = group;
                    [weakSelf setupAssets:nil];
                }
            }
            else
            {
                if (group.numberOfAssets > 0)
                    [weakSelf.groups addObject:group];
            }
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.groupPicker reloadData];
                if(endblock)
                    endblock();
            });
        }
    };
    
    ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
        [self showNotAllowed];
        [self.btnTitle setTitle:NSLocalizedStringFromTable(@"Not Allowed", @"ALAssetsPickerController",nil) forState:UIControlStateNormal];
		[self.btnTitle setImage:nil forState:UIControlStateNormal];
    };
    
    [self.assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll
                                      usingBlock:resultsBlock
                                    failureBlock:failureBlock];
}

- (void)setupAssets:(voidBlock)successBlock
{
    self.title = [self.assetsGroup valueForProperty:ALAssetsGroupPropertyName];
    
    if (!self.assets)
        self.assets = [[NSMutableArray alloc] init];
    else
        [self.assets removeAllObjects];
    
    if(!self.assetsGroup)
    {
        self.assetsGroup = self.groups[0];
    }
    [self.assetsGroup setAssetsFilter:self.assetsFilter];
    NSInteger assetCount = [self.assetsGroup numberOfAssets];
    ALAssetsGroupEnumerationResultsBlock resultsBlock = ^(ALAsset *asset, NSUInteger index, BOOL *stop) {
        if (asset)
        {
            [self.assets addObject:asset];
        }else if (self.assets.count >= assetCount)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self reloadData];
                if(successBlock)
                    successBlock();
            });
        }
    };
    [self.assetsGroup enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:resultsBlock];
}
- (void)reloadData
{
    [self.collectionView reloadData];
    [self showNoAssetsIfNeeded];
}
- (void)showNotAllowed
{
    self.title              = nil;
    
    UIView *lockedView      = [[UIView alloc] initWithFrame:self.collectionView.bounds];
    UIImageView *locked     = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"CameraPicker.bundle/Camera_ico_no_access"]];
    locked.contentMode      = UIViewContentModeCenter;
    
    CGRect rect             = CGRectInset(self.collectionView.bounds, 8, 8);
    UILabel *title          = [[UILabel alloc] initWithFrame:rect];
    UILabel *message        = [[UILabel alloc] initWithFrame:rect];
    
    title.text              = NSLocalizedStringFromTable(@"This app does not have access to your photos or videos.", @"ALAssetsPickerController",nil);
    title.font              = [UIFont boldSystemFontOfSize:17.0];
    title.textColor         = [UIColor colorWithRed:129.0/255.0 green:136.0/255.0 blue:148.0/255.0 alpha:1];
    title.textAlignment     = NSTextAlignmentCenter;
    title.numberOfLines     = 5;
    
    message.text            = NSLocalizedStringFromTable(@"You can enable access in Privacy Settings.", @"ALAssetsPickerController",nil);
    message.font            = [UIFont systemFontOfSize:14.0];
    message.textColor       = [UIColor colorWithRed:129.0/255.0 green:136.0/255.0 blue:148.0/255.0 alpha:1];
    message.textAlignment   = NSTextAlignmentCenter;
    message.numberOfLines   = 5;
    
    [title sizeToFit];
    [message sizeToFit];
    
    locked.center           = CGPointMake(lockedView.center.x, lockedView.center.y - locked.bounds.size.height /2 - 20);
    title.center            = locked.center;
    message.center          = locked.center;
    
    rect                    = title.frame;
    rect.origin.y           = locked.frame.origin.y + locked.frame.size.height + 10;
    title.frame             = rect;
    
    rect                    = message.frame;
    rect.origin.y           = title.frame.origin.y + title.frame.size.height + 5;
    message.frame           = rect;
    
    [lockedView addSubview:locked];
    [lockedView addSubview:title];
    [lockedView addSubview:message];
    [self.collectionView addSubview:lockedView];
}

- (void)showNoAssetsIfNeeded
{
    __weak typeof(self) weakSelf = self;
    
    voidBlock setNoImage = ^{
        UIImageView *imgView = (UIImageView *)[weakSelf.noAssetView viewWithTag:kTagNoAssetViewImageView];
        imgView.contentMode = UIViewContentModeCenter;
        imgView.image = [UIImage imageNamed:@"CameraPicker.bundle/Camera_ico_no_image"];
        
        UILabel *title = (UILabel *)[weakSelf.noAssetView viewWithTag:kTagNoAssetViewTitleLabel];
        title.text = NSLocalizedStringFromTable(@"No Photos", @"ALAssetsPickerController",nil);
        UILabel *msg = (UILabel *)[weakSelf.noAssetView viewWithTag:kTagNoAssetViewMsgLabel];
        msg.text = NSLocalizedStringFromTable(@"You can sync photos onto your iPhone using iTunes.",@"ALAssetsPickerController", nil);
    };
    
    if(self.assets.count ==0)
    {
        self.noAssetView.hidden = NO;
        setNoImage();
    }
    else
    {
        self.noAssetView.hidden = YES;
    }
}
#pragma mark - Collection View Data Source
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.assets.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = kAssetsViewCellIdentifier;
    ALCameraCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
	if (indexPath.row==0) { //第一个，放照相机
		[cell applyData:nil];
	}else{
		[cell applyData:[self.assets objectAtIndex:indexPath.row-1]];
	}
    return cell;
}

#pragma mark - Collection View Delegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
	if (indexPath.row==0) { //调出摄像头进行拍照
		ALAssetsPickerController *pickerSelf = (ALAssetsPickerController *)self;
	   ALCameraViewController *picker=[[ALCameraViewController alloc] init];
			[picker setSourceType:UIImagePickerControllerSourceTypeCamera];
		[picker setTheSuccessBlock:^(id sender,UIImage *image){
			if([pickerSelf.delegate respondsToSelector:@selector(ALAssetsPickerController:didFinishPickingImage:)]){
				[pickerSelf.delegate
				 ALAssetsPickerController:pickerSelf
				 didFinishPickingImage:image];
			[self dismissViewControllerAnimated:YES completion:^{
			}];
			}
		}];
		[self presentViewController:picker animated:YES completion:nil];
	}else{
	NSMutableArray *assets = [[NSMutableArray alloc] init];
		[assets addObject:[self.assets objectAtIndex:indexPath.row-1]];
	
	if([assets count]>0)
	{
		ALAssetsPickerController *picker = (ALAssetsPickerController *)self;
		if([picker.delegate respondsToSelector:@selector(ALAssetsPickerController:didFinishPickingAssets:)])
			[picker.delegate ALAssetsPickerController:picker didFinishPickingAssets:assets];
		[self dismissViewControllerAnimated:YES completion:^{
			
		}];
	}
	}
}
#pragma mark - Property
- (void)setTitle:(NSString *)title
{
    [super setTitle:title];
    [self.btnTitle setTitle:title forState:UIControlStateNormal];
	[self.btnTitle setImage:[UIImage imageNamed:@"CameraPicker.bundle/Camera_Down"] forState:UIControlStateNormal];
	[self.btnTitle setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
	[self.btnTitle setTitleEdgeInsets:UIEdgeInsetsMake(0, -28/2, 0, 28/2)];
	[self.btnTitle setImageEdgeInsets:UIEdgeInsetsMake(0, self.btnTitle.frame.size.width-28/2*2, 0, 0)];
    [self.btnTitle layoutIfNeeded];
}
- (void)menuArrowRotate
{
    [UIView animateWithDuration:0.35 animations:^{
        if(self.groupPicker.isOpen)
        {
            self.btnTitle.imageView.transform = CGAffineTransformMakeRotation(M_PI);
        }
        else
        {
            self.btnTitle.imageView.transform = CGAffineTransformIdentity;
        }
    } completion:^(BOOL finished) {
    }];
}
#pragma mark - Control Action
- (void)btnAction:(id)sender {
    UIButton *btn = (UIButton *)sender;
    switch (btn.tag) {
        case kTagButtonClose:
        {
            if([self.delegate respondsToSelector:@selector(ALAssetsPickerControllerDidCancel:)])
            {
            }
            [self dismissViewControllerAnimated:YES completion:^{
            }];
        }
            break;
        case kTagButtonGroupPicker:
        {
            [self.groupPicker toggle];
            [self menuArrowRotate];
        }
            break;
        default:
            break;
    }
}
@end
